<!DOCTYPE html>
<html>
    <head>
        <title locale="title/title">File Version History</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no">
        <link rel="stylesheet" href="../../script/semantic/semantic.css">
        <script type="text/javascript" src="../../script/jquery.min.js"></script>
        <script type="text/javascript" src="../../script/semantic/semantic.min.js"></script>
        <script type="text/javascript" src="../../script/ao_module.js"></script>
        <script type="text/javascript" src="../../script/applocale.js"></script>
        <link rel="stylesheet" href="../../script/ao.css">
        <style>
            body{
                background-color: var(--body_background);
            }
            .backgroundIcon{
                position: fixed;
                bottom: 0px;
                right: 0px;
                opacity: 0.3;
                margin-right: -8em;
                margin-bottom: -5em;
                z-index: -99;
                pointer-events: none;
                user-select: none;
            }
        </style>
    </head>
    <body id="filePropertiesWindow">
        <br>
        <div class="backgroundIcon">
            <img class="ui medium image" src="../../img/system/file-restore.svg">
        </div>
        <div class="ui container">
            <h3 class="ui header">
                <div class="content">
                    <span locale="title/title">File Version History</span>
                    <div class="sub header" locale="title/desc">Any file versions that is more than 30 days old will be automatically removed from the system.</div>
                </div>
            </h3>
            <button onclick="createSnapshot();" class="ui basic button"><i class="ui green add icon"></i> <span locale="button/newver">Create New Version</span></button>
            
            <div class="ui divider"></div>
            <div id="succ" style="display:none;" class="ui green message">
                <i class="ui green circle check icon"></i> <span id="msg">File Restore Succeed</span>
            </div>
            <div>
                <table class="ui very basic fluid celled table unstackable">
                    <tbody id="versions">
                      <tr>
                        <td>
                          <h4 class="ui header">
                                <div class="content">
                                <span locale="message/nofile/title">No File</span>
                                <div locale="message/nofile/desc" class="sub header">Invalid usage</div>
                            </div>
                            </h4>
                        </td>
                      </tr>
                    </tbody>
                  </table>
            </div>
            <div class="ui divider"></div>
            <button class="ui red  button" onclick="deleteAllVersions();"><i class="ui trash icon"></i> <span locale="button/removeAll">Remove All Version Histories</span></button>
            <br>
        </div>
        <script>
            var files = ao_module_loadInputFiles();
            var targetFile = "";
            var currentVersionList = [];
            if (files.length >= 1){
                targetFile = files[0];
                applocale.init("../../SystemAO/locale/file_versions.json", function(){
                    applocale.translate();
                    loadVersionHistory(targetFile);
                    initTheme();
                });
                
                setInterval(function(){
                    checkHistoryListUpdate(targetFile);
                }, 3000)
            }else{
                //No file selected
                applocale.init("../../SystemAO/locale/file_versions.json", function(){
                    applocale.translate();
                    initTheme();
                });
            }

            function initTheme(){
                //Load system theme
                $.get("../../system/file_system/preference?key=" + "file_explorer/theme",function(data){
                    if (data.error === undefined){
                        if (data == "darkTheme"){
                            $("body").addClass("darkTheme");
                            $("#succ").attr("class","ui black message");
                        }else{
                            $("body").addClass("whiteTheme");
                        }
                    }
                });
            }

            function checkHistoryListUpdate(vpath){
                $.ajax({
                    url: "../../system/file_system/versionHistory",
                    data: {path: vpath},
                    method: "POST",
                    success: function(data){
                        if (data.error == undefined){
                            if (currentVersionList.length != data.Versions.length){
                                loadVersionHistory(vpath);
                            }
                        }
                    }
                });
            }

            function loadVersionHistory(vpath){
                $("#versions").html("Loading...");
                $.ajax({
                    url: "../../system/file_system/versionHistory",
                    data: {path: vpath},
                    method: "POST",
                    success: function(data){
                        if (data.error !== undefined){
                            alert(data.error);
                        }else{
                            $("#versions").html("");
                            currentVersionList = data.Versions;
                            data.Versions.forEach(fileVersionEntry => {
                                var filesize = ao_module_utils.formatBytes(fileVersionEntry.Filesize, 1);
                                $("#versions").append(`<tr>
                                    <td>
                                    <h4 class="ui header">
                                        <div class="content">
                                        <span>${fileVersionEntry.Filename}</span>
                                        <div class="sub header">${fileVersionEntry.OverwriteTime} / ${filesize}</div>
                                    </div>
                                    </h4></td>
                                    <td>
                                        <div class="ui icon mini buttons">
                                            <button relpath="${fileVersionEntry.Relpath}" onclick="downloadVersion(this);" class="ui very basic icon button" title="${applocale.getString("title/download", "Download Version")}"><i class="ui blue download icon"></i></button>
                                            <button verid="${fileVersionEntry.HistoryID}" onclick="restoreVersion(this);" class="ui very basic icon button" title="${applocale.getString("title/restore", "Restore This Version")}"><i class="ui green history icon"></i></button>
                                            <button verid="${fileVersionEntry.HistoryID}" onclick="deleteVersion(this);" class="ui very basic icon button" title="${applocale.getString("title/delete", "Delete")}"><i class="ui red trash icon"></i></button>
                                        </div>
                                        
                                    </td>
                                </tr>`);
                            });

                            if (data.Versions.length == 0){
                                //This file has no version history
                                $("#versions").html(`<tr>
                                    <td>
                                        <h4 class="ui header">
                                            <div class="content">
                                                <i class="ui history icon"></i><span> ${applocale.getString("message/nohist/title", "No History")}</span>
                                                <div class="sub header">${applocale.getString("message/nohist/desc", "This file has no previous version histories.")}</div>
                                            </div>
                                        </h4>
                                    </td>
                                </tr>`);
                            }
                            applocale.translate();
                        }
                    }
                });
            }

            function downloadVersion(object){
                var relpath = $(object).attr("relpath");
                var dirname = targetFile.split("/");
                dirname.pop();
                var accessPath = dirname.join("/") + "/" + relpath;
                window.open("../../media/download?file=" + accessPath)
            }

            function createSnapshot(){
                //Create a snapshot of the current object
                $.ajax({
                    url: "../../system/file_system/versionHistory",
                    data: {path: targetFile, opr: "new"},
                    method: "POST",
                    success: function(data){
                        if (data.error != undefined){
                            alert(data.error)
                        }else{
                            msgbox(applocale.getString("msgbox/created","New Version Created"));
                            loadVersionHistory(targetFile);
                        }
                    }
                });
            }

            function restoreVersion(object){
                var versionID = $(object).attr("verid");
                if (confirm(applocale.getString("warning/restore", "Restoring this file will remove all newer version histories of this file. Confirm?"))){
                    $.ajax({
                        url: "../../system/file_system/versionHistory",
                        data: {path: targetFile, opr: "restore", histid: versionID},
                        method: "POST",
                        success: function(data){
                            if (data.error != undefined){
                                alert(data.error)
                            }else{
                                loadVersionHistory(targetFile);
                                msgbox(applocale.getString("msgbox/restored","Restore Succeed"));
                            }
                        }
                    });
                }
            }

            function msgbox(message){
                $("#msg").text(message);
                $("#succ").stop().finish().fadeIn("fast").delay(3000).fadeOut("fast");
            }

            function deleteVersion(object){
                var versionID = $(object).attr("verid");
                $.ajax({
                    url: "../../system/file_system/versionHistory",
                    data: {path: targetFile, opr: "delete", histid: versionID},
                    method: "POST",
                    success: function(data){
                        if (data.error != undefined){
                            alert(data.error)
                        }else{
                            loadVersionHistory(targetFile);
                        }
                    }
                });
            }

            function deleteAllVersions(object){
                var versionID = $(object).attr("verid");
                if (confirm(applocale.getString("warning/deleteall", "This operation will **PERMANENTLY DELETE ALL** version history of this file. Confirm?"))){
                    $.ajax({
                        url: "../../system/file_system/versionHistory",
                        data: {path: targetFile, opr: "deleteAll", histid: versionID},
                        method: "POST",
                        success: function(data){
                            if (data.error != undefined){
                                alert(data.error)
                            }else{
                                msgbox(applocale.getString("msgbox/deletedall","All version history deleted"));
                                loadVersionHistory(targetFile);
                            }
                        }
                    });
                }
                
            }
             
        </script>
    </body>
</html> 